import {
    validatenull
  } from './validate'
  import request from '@/router/axios'
  import * as CryptoJS from 'crypto-js'
  
  // 表单序列化
  export const serialize = data => {
    const list = []
    Object.keys(data).forEach(ele => {
      list.push(`${ele}=${data[ele]}`)
    })
    return list.join('&')
  }
  export const getObjType = obj => {
    var toString = Object.prototype.toString
    var map = {
      '[object Boolean]': 'boolean',
      '[object Number]': 'number',
      '[object String]': 'string',
      '[object Function]': 'function',
      '[object Array]': 'array',
      '[object Date]': 'date',
      '[object RegExp]': 'regExp',
      '[object Undefined]': 'undefined',
      '[object Null]': 'null',
      '[object Object]': 'object'
    }
    if (obj instanceof Element) {
      return 'element'
    }
    return map[toString.call(obj)]
  }
  /**
   * 对象深拷贝
   */
  export const deepClone = data => {
    var type = getObjType(data)
    var obj
    if (type === 'array') {
      obj = []
    } else if (type === 'object') {
      obj = {}
    } else {
      // 不再具有下一层次
      return data
    }
    if (type === 'array') {
      for (var i = 0, len = data.length; i < len; i++) {
        obj.push(deepClone(data[i]))
      }
    } else if (type === 'object') {
      for (var key in data) {
        obj[key] = deepClone(data[key])
      }
    }
    return obj
  }
  /**
   * 判断路由是否相等
   */
  export const diff = (obj1, obj2) => {
    delete obj1.close
    var o1 = obj1 instanceof Object
    var o2 = obj2 instanceof Object
    if (!o1 || !o2) {
      /*  判断不是对象  */
      return obj1 === obj2
    }
  
    if (Object.keys(obj1).length !== Object.keys(obj2).length) {
      return false
      // Object.keys() 返回一个由对象的自身可枚举属性(key值)组成的数组,例如：数组返回下表：let arr = ["a", "b", "c"];console.log(Object.keys(arr))->0,1,2;
    }
  
    for (var attr in obj1) {
      var t1 = obj1[attr] instanceof Object
      var t2 = obj2[attr] instanceof Object
      if (t1 && t2) {
        return diff(obj1[attr], obj2[attr])
      } else if (obj1[attr] !== obj2[attr]) {
        return false
      }
    }
    return true
  }
  /**
   * 设置灰度模式
   */
  export const toggleGrayMode = (status) => {
    if (status) {
      document.body.className = document.body.className + ' grayMode'
    } else {
      document.body.className = document.body.className.replace(' grayMode', '')
    }
  }
  /**
   * 设置主题
   */
  export const setTheme = (name) => {
    document.body.className = name
  }
  
  /**
   *加密处理
   */
  export const encryption = (params) => {
    let {
      data,
      type,
      param,
      key
    } = params
    const result = JSON.parse(JSON.stringify(data))
    if (type === 'Base64') {
      param.forEach(ele => {
        result[ele] = btoa(result[ele])
      })
    } else {
      param.forEach(ele => {
        var data = result[ele]
        key = CryptoJS.enc.Latin1.parse(key)
        var iv = key
        // 加密
        var encrypted = CryptoJS.AES.encrypt(
          data,
          key, {
            iv: iv,
            mode: CryptoJS.mode.CFB,
            padding: CryptoJS.pad.NoPadding
          })
        result[ele] = encrypted.toString()
      })
    }
    return result
  }
  
  /**
   * 浏览器判断是否全屏
   */
  export const fullscreenToggel = () => {
    if (fullscreenEnable()) {
      exitFullScreen()
    } else {
      reqFullScreen()
    }
  }
  /**
   * esc监听全屏
   */
  export const listenfullscreen = (callback) => {
    function listen() {
      callback()
    }
  
    document.addEventListener('fullscreenchange', function () {
      listen()
    })
    document.addEventListener('mozfullscreenchange', function () {
      listen()
    })
    document.addEventListener('webkitfullscreenchange', function () {
      listen()
    })
    document.addEventListener('msfullscreenchange', function () {
      listen()
    })
  }
  /**
   * 浏览器判断是否全屏
   */
  export const fullscreenEnable = () => {
    return document.isFullScreen || document.mozIsFullScreen || document.webkitIsFullScreen
  }
  
  /**
   * 浏览器全屏
   */
  export const reqFullScreen = () => {
    if (document.documentElement.requestFullScreen) {
      document.documentElement.requestFullScreen()
    } else if (document.documentElement.webkitRequestFullScreen) {
      document.documentElement.webkitRequestFullScreen()
    } else if (document.documentElement.mozRequestFullScreen) {
      document.documentElement.mozRequestFullScreen()
    }
  }
  /**
   * 浏览器退出全屏
   */
  export const exitFullScreen = () => {
    if (document.documentElement.requestFullScreen) {
      document.exitFullScreen()
    } else if (document.documentElement.webkitRequestFullScreen) {
      document.webkitCancelFullScreen()
    } else if (document.documentElement.mozRequestFullScreen) {
      document.mozCancelFullScreen()
    }
  }
  /**
   * 递归寻找子类的父类
   */
  
  export const findParent = (menu, id) => {
    for (let i = 0; i < menu.length; i++) {
      if (menu[i].children.length !== 0) {
        for (let j = 0; j < menu[i].children.length; j++) {
          if (menu[i].children[j].id === id) {
            return menu[i]
          } else {
            if (menu[i].children[j].children.length !== 0) {
              return findParent(menu[i].children[j].children, id)
            }
          }
        }
      }
    }
  }
  
  //获取n天前或n天后的日期
  export const getOldOrNewTime = (n) => {
    var currentDate = new Date()
    var preDate = new Date(currentDate.getTime() + n * 24 * 3600 * 1000)
    let year = preDate.getFullYear()
    let mon = preDate.getMonth() + 1
    let day = preDate.getDate()
    let oldOrNewTime = year + '-' + (mon < 10 ? ('0' + mon) : mon) + '-' + (day < 10 ? ('0' + day) : day)
    return oldOrNewTime
  }
  
  /**
   * 时间日期格式化
   */
  export const dateTimeFormatter = function (date, format = 'yyyy-MM-dd hh:mm:ss') {
    // 时间格式化辅助函数 date:毫秒数(number类型) format:'yyyy-MM-dd hh:mm:ss'
    // toUTCString() 方法可根据世界时 (UTC) 把 Date 对象转换为字符串，并返回结果。
    // console.log(date, date.toUTCString())
    if (!date || date == "" || date.toUTCString() == "Invalid Date") {
      return "";
    }
  
    date = new Date(date);
  
    const map = {
      M: date.getMonth() + 1, // 月份
      d: date.getDate(), // 日
      h: date.getHours(), // 小时
      m: date.getMinutes(), // 分
      s: date.getSeconds(), // 秒
      q: Math.floor((date.getMonth() + 3) / 3), // 季度
      S: date.getMilliseconds(), // 毫秒
    };
    format = format.replace(/([yMdhmsqS])+/g, (all, t) => {
      let v = map[t];
      if (v !== undefined) {
        if (all.length > 1) {
          v = "0" + v;
          v = v.substr(v.length - 2);
        }
        return v;
      } else if (t === "y") {
        return (date.getFullYear() + "").substr(4 - all.length);
      }
      return all;
    });
    return format;
  };
  export const dateTimeFormatterNew = function (date, format = 'yyyy-MM-dd hh:mm:ss') {
    // 时间格式化辅助函数 date:毫秒数(number类型) format:'yyyy-MM-dd hh:mm:ss'
    // toUTCString() 方法可根据世界时 (UTC) 把 Date 对象转换为字符串，并返回结果。
    if (!date || date === "") {
      return "";
    }
  
    date = new Date(date);
  
    const map = {
      M: date.getMonth() + 1, // 月份
      d: date.getDate(), // 日
      h: date.getHours(), // 小时
      m: date.getMinutes(), // 分
      s: date.getSeconds(), // 秒
      q: Math.floor((date.getMonth() + 3) / 3), // 季度
      S: date.getMilliseconds(), // 毫秒
    };
    format = format.replace(/([yMdhmsqS])+/g, (all, t) => {
      let v = map[t];
      if (v !== undefined) {
        if (all.length > 1) {
          v = "0" + v;
          v = v.substr(v.length - 2);
        }
        return v;
      } else if (t === "y") {
        return (date.getFullYear() + "").substr(4 - all.length);
      }
      return all;
    });
    return format;
  };
  
  /**
   * 动态插入css
   */
  
  export const loadStyle = url => {
    const link = document.createElement('link')
    link.type = 'text/css'
    link.rel = 'stylesheet'
    link.href = url
    const head = document.getElementsByTagName('head')[0]
    head.appendChild(link)
  }
  /**
   * 判断路由是否相等
   */
  export const isObjectValueEqual = (a, b) => {
    let result = true
    Object.keys(a).forEach(ele => {
      const type = typeof (a[ele])
      if (type === 'string' && a[ele] !== b[ele]) result = false
      else if (type === 'object' && JSON.stringify(a[ele]) !== JSON.stringify(b[ele])) result = false
    })
    return result
  }
  /**
   * 根据字典的value显示label
   */
  export const findByvalue = (dic, value) => {
    let result = ''
    if (validatenull(dic)) return value
    if (typeof (value) === 'string' || typeof (value) === 'number' || typeof (value) === 'boolean') {
      let index = 0
      index = findArray(dic, value)
      if (index !== -1) {
        result = dic[index].label
      } else {
        result = value
      }
    } else if (value instanceof Array) {
      result = []
      let index = 0
      value.forEach(ele => {
        index = findArray(dic, ele)
        if (index !== -1) {
          result.push(dic[index].label)
        } else {
          result.push(value)
        }
      })
      result = result.toString()
    }
    return result
  }
  /**
   * 根据字典的value查找对应的index
   */
  export const findArray = (dic, value) => {
    for (let i = 0; i < dic.length; i++) {
      if (dic[i].value === value) {
        return i
      }
    }
    return -1
  }
  /**
   * 生成随机len位数字
   */
  export const randomLenNum = (len, date) => {
    let random = ''
    random = Math.ceil(Math.random() * 100000000000000).toString().substr(0, len || 4)
    if (date) random = random + Date.now()
    return random
  }
  /**
   * 打开小窗口
   */
  export const openWindow = (url, title, w, h) => {
    // Fixes dual-screen position                            Most browsers       Firefox
    const dualScreenLeft = window.screenLeft !== undefined ? window.screenLeft : screen.left
    const dualScreenTop = window.screenTop !== undefined ? window.screenTop : screen.top
  
    const width = window.innerWidth ? window.innerWidth : document.documentElement.clientWidth ? document.documentElement.clientWidth : screen.width
    const height = window.innerHeight ? window.innerHeight : document.documentElement.clientHeight ? document.documentElement.clientHeight : screen.height
  
    const left = ((width / 2) - (w / 2)) + dualScreenLeft
    const top = ((height / 2) - (h / 2)) + dualScreenTop
    const newWindow = window.open(url, title, 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=yes, copyhistory=no, width=' + w + ', height=' + h + ', top=' + top + ', left=' + left)
  
    // Puts focus on the newWindow
    if (window.focus) {
      newWindow.focus()
    }
  }
  
  /**
   *  <img> <a> src 处理
   * @returns {PromiseLike<T | never> | Promise<T | never>}
   */
  export function handleImg(url, id) {
    return validatenull(url) ? null : request({
      url: url,
      method: 'get',
      responseType: 'blob'
    }).then((response) => { // 处理返回的文件流
      const blob = response.data
      const img = document.getElementById(id)
      img.src = URL.createObjectURL(blob)
      window.setTimeout(function () {
        window.URL.revokeObjectURL(blob)
      }, 0)
    })
  }
  
  export function handleDown(filename, bucket) {
    return request({
      url: '/admin/sys-file/' + bucket + '/' + filename,
      method: 'get',
      responseType: 'blob'
    }).then((response) => { // 处理返回的文件流
      const blob = response.data
      const link = document.createElement('a')
      link.href = URL.createObjectURL(blob)
      link.download = filename
      document.body.appendChild(link)
      link.click()
      window.setTimeout(function () {
        URL.revokeObjectURL(blob)
        document.body.removeChild(link)
      }, 0)
    })
  }
  
  export function getQueryString(url, paraName) {
    const arrObj = url.split('?')
    if (arrObj.length > 1) {
      const arrPara = arrObj[1].split('&')
      let arr
      for (let i = 0; i < arrPara.length; i++) {
        arr = arrPara[i].split('=')
        // eslint-disable-next-line eqeqeq
        if (arr != null && arr[0] == paraName) {
          return arr[1]
        }
      }
      return ''
    } else {
      return ''
    }
  }
  
  // 删除对象中属性对应值未的属性
  export function delAttriWithValueEmpty(p_object) {
    let _object = deepClone(p_object)
  
    for (const [key, value] of Object.entries(_object)) {
      if (!value) {
        delete _object[key];
      }
    }
  
    return _object
  }
  
  
  /**
   * 判断属性是否空
   * @param str
   * @returns {boolean}
   */
  export const isEmpty = (str) => {
    if (str === "" || str == null || str === undefined) {
      return true;
    }
    if (str instanceof Array) {
      if (str == null || str.length <= 0) {
        return true;
      }
    }
  
    return false;
  };
  
  export const objToFilter = (o, sign = ";") => {
    const str = [];
    for (const p in o) {
      if (!isEmpty(o[p])) {
        str.push(p + "=" + o[p]);
      }
    }
    return str.join(sign);
  };
  
  
  // 搜索条件时间格式化(2021-09-08 00:00:00)
  export function formatDatetime(date, key, props) {
    let _datetime = JSON.parse(JSON.stringify(date));
  
    if (_datetime[key] && _datetime[key].length > 0) {
      _datetime = {
        ..._datetime,
      };
  
      _datetime[props[0]] = `${_datetime[key][0]}`;
      _datetime[props[1]] = `${_datetime[key][1]}`;
  
      delete _datetime[key];
    }
  
    return _datetime;
  }
  
  
  // 生成下载文件
  export function createDownFile(res, filename) {
    const link = document.createElement("a");
    let blob = new Blob([res.data], {
      type: "application/vnd.ms-excel;charset=utf-8"
    });
    link.style.display = "none";
    //设置连接
    link.href = URL.createObjectURL(blob);
    link.download = filename;
    document.body.appendChild(link);
    //模拟点击事件
    link.click();
  }
  
  // 加
  export function floatAdd(_this, arg) {
    let r1, r2, m, n;
    try {
      r1 = _this.toString().split(".")[1].length;
    } catch (e) {
      r1 = 0;
    }
    try {
      r2 = arg.toString().split(".")[1].length;
    } catch (e) {
      r2 = 0;
    }
    m = Math.pow(10, Math.max(r1, r2));
    // 动态控制精度长度
    n = r1 >= r2 ? r1 : r2;
    return parseFloat(((_this * m + arg * m) / m).toFixed(n));
  }
  
  // 减
  export function floatSub(_this, arg) {
    let r1, r2, m, n;
    try {
      r1 = _this.toString().split(".")[1].length;
    } catch (e) {
      r1 = 0;
    }
    try {
      r2 = arg.toString().split(".")[1].length;
    } catch (e) {
      r2 = 0;
    }
    m = Math.pow(10, Math.max(r1, r2));
    // 动态控制精度长度
    n = r1 >= r2 ? r1 : r2;
    return parseFloat(((_this * m - arg * m) / m).toFixed(n));
  }
  
  // 乘
  export function floatMul(_this, arg) {
    let m = 0,
      s1 = _this.toString(),
      s2 = arg.toString();
    try {
      m += s1.split(".")[1].length;
    } catch (e) {
    }
    try {
      m += s2.split(".")[1].length;
    } catch (e) {
    }
    return parseFloat(
      (
        (Number(s1.replace(".", "")) * Number(s2.replace(".", ""))) /
        Math.pow(10, m)
      ).toString()
    );
  }
  
  // 除
  export function floatDiv(_this, arg) {
    let t1 = 0,
      t2 = 0,
      r1,
      r2;
    try {
      t1 = _this.toString().split(".")[1].length;
    } catch (e) {
    }
    try {
      t2 = arg.toString().split(".")[1].length;
    } catch (e) {
    }
    try {
      r1 = Number(_this.toString().replace(".", ""));
    } catch (e) {
      r1 = 0;
    }
    try {
      r2 = Number(arg.toString().replace(".", ""));
    } catch (e) {
      r2 = 0;
    }
  
    let n = t1 > t2 ? t1 > 2 ? 2 : t1 : t2 > 2 ? 2 : t2;
    return parseFloat(floatMul(r1 / r2, Math.pow(10, t2 - t1))).toFixed(n);
  }
  
  // 校验确认文件类型
  export function checkFileType(file) {
    const lowUrl = file.toString().toLowerCase();
  
    if (
      lowUrl.includes(".png") ||
      lowUrl.includes(".jpg") ||
      lowUrl.includes(".jpeg")
    ) {
      return "img";
    }
  
    if (lowUrl.includes(".pdf")) {
      return "pdf";
    }
  
    if (lowUrl.includes(".doc") || lowUrl.includes(".docx")) {
      return "word";
    }
  
    if (lowUrl.includes(".xlsx") || lowUrl.includes(".xls")) {
      return "excel";
    }
  
    return "img";
  
  }
  
  // Excel文件导出
  export function downloadFile(data, name, endName = ".xls") {
    const url = window.URL.createObjectURL(new Blob([data]));
    const link = document.createElement("a");
    link.style.display = "none";
    link.href = url;
    const time = dateTimeFormatter(new Date(), "yyyy-MM-dd");
    link.setAttribute("download", name + endName);
    document.body.appendChild(link);
    link.click();
  }
  
  // PDF文件导出
  export function downloadPdf(data, name) {
    const url = window.URL.createObjectURL(new Blob([data]));
    const link = document.createElement("a");
    link.style.display = "none";
    link.href = url;
    const time = dateTimeFormatter(new Date(), "yyyy-MM-dd");
    link.setAttribute("download", name + time + ".pdf");
    document.body.appendChild(link);
    link.click();
  }
  
  export function calcWindowResize() {
    const $avues = document.getElementsByClassName("avue-affixed");
    const $view = document.querySelector(".sys-view-scrollbar");
    if ($avues && $view) {
      const clientHeight = $view.clientHeight;
  
      for (let i = 0; i < $avues.length; i++) {
        const $node = $avues.item(i);
        // let top = $node.offsetTop;
        const top =
          $node.getBoundingClientRect().top -
          $view.getBoundingClientRect().top;
        let height = clientHeight - top;
        const $page = $node.querySelector(".avue-crud__pagination");
        if ($page) {
          const pageHeight = $page.clientHeight;
          height -= pageHeight;
        }
  
        const $tableHeader = $node.querySelector(
          ".el-table__header-wrapper"
        );
        let headerHeight = 0;
        if ($tableHeader) {
          headerHeight = $tableHeader.clientHeight;
        }
  
        const $table = $node.querySelector(".el-table");
        const $tableBody = $node.querySelector(".el-table__body-wrapper");
        const $fixed = $node.querySelector(".el-table__fixed");
        const $fixedRight = $node.querySelector(".el-table__fixed-right");
        const $fixFooterHeight = $node.querySelector(".el-table__footer-wrapper");
        //合计栏  el-table__fixed-footer-wrapper
        const fixFooterHeight = $fixFooterHeight ? 31 : 0
        //    console.log(fixFooterHeight)
        $table.style.height = height - 10 + "px";
        // $table.style.right = "7px";
        $tableBody.style.height = height - 10 - headerHeight - fixFooterHeight + "px";
        if ($fixed) {
          $fixed.style.height = height + "px";
  
          // $fixed.style.bottom = "7px";
          $fixed.querySelector(
            ".el-table__fixed-body-wrapper"
          ).style.height = height - headerHeight - 19 - fixFooterHeight + "px"; //akido/01/14 -7
          $fixed.querySelector(
            ".el-table__fixed-body-wrapper"
          ).style.top = headerHeight + "px";
        }
        if ($fixedRight) {
          $fixedRight.style.height = height + "px";
          // $fixedRight.style.bottom = "7px";
          // $fixedRight.style.right = "7px";
          $fixedRight.querySelector(
            ".el-table__fixed-body-wrapper"
          ).style.height = height - headerHeight - 19 - fixFooterHeight + "px"; //akido/01/14 -7
          $fixedRight.querySelector(
            ".el-table__fixed-body-wrapper"
          ).style.top = headerHeight + "px";
        }
      }
    }
  }
  
  //处理导入时后端返回的数据
  export function judgeErrorByResponseType(response) {
    return new Promise((resolve, reject) => {
      console.log('response = ', response.headers);
      if (response.headers['content-type'].includes('json')) {
        // 此处拿到的data才是blob
        const {
          data
        } = response
        const reader = new FileReader()
        reader.onload = () => {
          const {
            result
          } = reader
          const errorInfos = JSON.parse(result)
          resolve(errorInfos)
        }
        reader.readAsText(data)
      } else {
        resolve(response)
      }
    })
  }
  
  // 智能输入大于0的数字
  export function inputFloatFunc(val, limit = 0) {
    if (val) {
      val = val.replace(/[^\d.]/g, ""); //保留数字
      val = val.replace(/^00/, "0."); //开头不能有两个0
      val = val.replace(/^\./g, "0."); //开头为小数点转换为0.
      val = val.replace(/\.{2,}/g, "."); //两个以上的小数点转换成一个
      val = val.replace(".", "$#$").replace(/\./g, "").replace("$#$", "."); //只保留一个小数点
      /^0\d+/.test(val) ? val = val.slice(1) : ''; //两位以上数字开头不能为0
      const str = '^(\\d+)\\.(\\d{' + limit + '}).*$'
      const reg = new RegExp(str)
      if (limit === 0) {
        // 不需要小数点
        val = val.replace(reg, '$1')
      } else if (limit === -1) {
  
      } else {
        // 通过正则保留小数点后指定的位数
        val = val.replace(reg, '$1.$2')
      }
      return val
    }
  }
  
  
  /* 获取今天 */
  export const today = () => {
    let _d = new Date();
    let y = _d.getFullYear();
    let m = _d.getMonth() + 1;
    let d = _d.getDate();
    return `${y}-${m}-${d}`;
  };
  export const groupBy = (arr, prop, method) => {
    if (method === 'reduce') {
      return arr.reduce((result, item) => {
        const key = item[prop];
        if (!result[key]) {
          result[key] = [];
        }
        result[key].push(item);
        return result;
      }, {});
    } else if (method === 'forEach') {
      let grouped = {};
      arr.forEach(item => {
        const key = item[prop];
        if (!grouped[key]) {
          grouped[key] = [];
        }
        grouped[key].push(item);
      });
      return grouped;
    } else if (method === 'map') {
      let grouped = Object.create(null);
      arr.map(item => {
        const key = item[prop];
        if (!grouped[key]) {
          grouped[key] = [];
        }
        grouped[key].push(item);
      });
      return grouped;
    } else if (method === 'mapObj') {
      let grouped = new Map();
      arr.forEach(item => {
        const key = item[prop];
        const group = grouped.get(key) || [];
        group.push(item);
        grouped.set(key, group);
      });
      return Object.fromEntries(grouped);
    } else if (method === 'lodash') {
      const _ = require('lodash');
      return _.groupBy(arr, prop);
    } else if (method === 'mapArrow') {
      let grouped = new Map();
      arr.forEach(item => {
        const key = item[prop];
        const group = grouped.get(key) || [];
        group.push(item);
        grouped.set(key, group);
      });
      return Object.fromEntries(grouped);
    } else {
      return {};
    }
  }
  export const arrGroup = (arr, fn) => {
    const obj = {};
    arr.forEach(item => {
      const key = JSON.stringify(fn(item));
      obj[key] = obj[key] || [];
      obj[key].push(item)
    });
    return Object.keys(obj).map(k => {
      return obj[k];
    })
  }
  
  //时间戳转换
  export const formatDateTime=(date)=> {
    var date = new Date(date);
    var YY = date.getFullYear() + '-';
    var MM = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
    var DD = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate());
    var hh = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
    var mm = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':';
    var ss = (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds());
    return YY + MM + DD +" "+hh + mm + ss;
  }
  
  export function groupArrByKey (arr, key) {
    let dataArr = [];
    arr.map(mapItem => {
      if (dataArr.length === 0) {
        dataArr.push({ [key]: mapItem[key], children: [mapItem] })
      } else {
        let res = dataArr.some(item=> {//判断相同，有就添加到当前项
          if (item[key] === mapItem[key]) {
            item.children.push(mapItem)
            return true
          }
        })
        if (!res) {//如果没找相同日期添加一个新对象
          dataArr.push({ [key]: mapItem[key], children: [mapItem] })
        }
      }
    })
    return dataArr
  }
  
  
  export const getDictLabel = (value, dictList) => {
    let label = ''
    dictList.forEach( item => {
      if (item.value === value) {
        label = item.label
      }
    })
    return label
  }
  